package com.platform.wechat.common;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author CX
 * @create 2021-07-12 11:50
 */
public class HttpClientUtil {

    public static String doGet(String url){
        //返回的结果
        String result = null;
        //创建请求方式为HTTPGET请求
        HttpGet httpGet = new HttpGet(url);
        //创建客户端
        HttpClient httpClient = new DefaultHttpClient();
        try {
            result = getString(result, httpClient.execute(httpGet));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String getString(String result, HttpResponse execute) {
        try {
            //执行发送请求并得到返回结果
            HttpResponse httpResponse = execute;
            //验证请求是否成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String doPost(String url, String data){
        //返回的结果
        String result = null;
        //创建请求方式为HTTPGET请求
        HttpPost httpPost = new HttpPost(url);
        //创建客户端
        HttpClient httpClient = new DefaultHttpClient();
        //将请求中所需要携带的参数放入post请求体中
        httpPost.setEntity(new StringEntity(data,"utf-8"));
        try {
            result = getString(result, httpClient.execute(httpPost));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
